import Taro, { useRouter as useTaroRouter } from '@tarojs/taro'
import { useCallback } from 'react'

export interface NavigateOptions {
  /** 页面路径 */
  url: string
  /** 路径参数 */
  params?: Record<string, any>
  /** 成功回调 */
  success?: () => void
  /** 失败回调 */
  fail?: (error: any) => void
}

/**
 * useNavigation Hook
 * 提供类型安全的路由跳转方法
 */
export const useNavigation = () => {
  const router = useTaroRouter()

  /**
   * 构建URL（带参数）
   */
  const buildUrl = useCallback((url: string, params?: Record<string, any>): string => {
    if (!params || Object.keys(params).length === 0) {
      return url
    }

    const queryString = Object.entries(params)
      .map(([key, value]) => `${key}=${encodeURIComponent(String(value))}`)
      .join('&')

    return `${url}?${queryString}`
  }, [])

  /**
   * 跳转到新页面
   */
  const navigateTo = useCallback(
    (options: string | NavigateOptions) => {
      const { url, params, success, fail } = typeof options === 'string' ? { url: options } : options

      const finalUrl = buildUrl(url, params)
      Taro.navigateTo({
        url: finalUrl,
        success,
        fail,
      })
    },
    [buildUrl],
  )

  /**
   * 替换当前页面
   */
  const redirectTo = useCallback(
    (options: string | NavigateOptions) => {
      const { url, params, success, fail } = typeof options === 'string' ? { url: options } : options

      const finalUrl = buildUrl(url, params)

      Taro.redirectTo({
        url: finalUrl,
        success,
        fail,
      })
    },
    [buildUrl],
  )

  /**
   * 返回上一页
   */
  const navigateBack = useCallback((delta: number = 1) => {
    Taro.navigateBack({ delta })
  }, [])

  /**
   * 跳转到 tabBar 页面
   */
  const switchTab = useCallback((url: string) => {
    Taro.redirectTo({ url })
  }, [])

  /**
   * 重新加载当前页面
   */
  const reLaunch = useCallback(
    (options: string | NavigateOptions) => {
      const { url, params, success, fail } = typeof options === 'string' ? { url: options } : options

      const finalUrl = buildUrl(url, params)

      Taro.reLaunch({
        url: finalUrl,
        success,
        fail,
      })
    },
    [buildUrl],
  )

  /**
   * 获取当前页面路径
   */
  const getCurrentPath = useCallback((): string => {
    const pages = Taro.getCurrentPages()
    if (pages.length > 0) {
      return `/${pages[pages.length - 1].route}`
    }
    return ''
  }, [])

  /**
   * 获取当前页面参数
   */
  const getCurrentParams = useCallback((): Record<string, any> => {
    return router?.params || {}
  }, [router])

  /**
   * 判断是否可以返回
   */
  const canGoBack = useCallback((): boolean => {
    const pages = Taro.getCurrentPages()
    return pages.length > 1
  }, [])

  // 便捷方法：跳转到常用页面
  const goHome = useCallback(() => {
    switchTab('/pages/home/index')
  }, [switchTab])

  const goOrder = useCallback(() => {
    switchTab('/pages/order/index')
  }, [switchTab])

  const goProfile = useCallback(() => {
    switchTab('/pages/profile/index')
  }, [switchTab])

  const goOrderDetails = useCallback(
    (orderId: string) => {
      navigateTo({
        url: '/pages/order-details/index',
        params: { id: orderId },
      })
    },
    [navigateTo],
  )

  const goProductDetails = useCallback(
    (productId: string) => {
      navigateTo({
        url: '/pages/product-details/index',
        params: { id: productId },
      })
    },
    [navigateTo],
  )

  const goEditAddress = useCallback(
    (addressId?: string) => {
      navigateTo({
        url: '/pages/edit-address/index',
        params: addressId ? { id: addressId } : undefined,
      })
    },
    [navigateTo],
  )

  return {
    // 基础方法
    navigateTo,
    redirectTo,
    navigateBack,
    switchTab,
    reLaunch,

    // 工具方法
    buildUrl,
    getCurrentPath,
    getCurrentParams,
    canGoBack,

    // 便捷方法
    goHome,
    goOrder,
    goProfile,
    goOrderDetails,
    goProductDetails,
    goEditAddress,

    // router 信息
    path: router?.path || '',
    params: router?.params || {},
  }
}

export default useNavigation
